package com.qf.fmall2202.order.scheduled;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qf.fmall2202.order.entity.OrderItem;
import com.qf.fmall2202.order.entity.Orders;
import com.qf.fmall2202.order.service.OrderItemService;
import com.qf.fmall2202.order.service.OrdersService;
import com.qf.fmall2202.product.entity.ProductSku;
import com.qf.fmall2202.product.service.ProductSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Component
public class checkOrderTime {
    @Autowired
    private ProductSkuService productSkuService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private OrdersService ordersService;

    @Scheduled(cron = "0/5 * * * * ?")
    public void checkOrderTime() {
        long nowTime = new Date().getTime() - (1000 * 60 * 15);
        List<Orders> ordersList = ordersService.list(new LambdaQueryWrapper<Orders>().ne(Orders::getStatus, "6").apply("UNIX_TIMESTAMP(create_time) < " + nowTime));
        if (ordersList.size() > 0) {
            List<String> ordersIdList = ordersList.stream().map(Orders::getOrderId).collect(Collectors.toList());
            List<OrderItem> orderItemList = orderItemService.list(new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderId, ordersIdList));
            Map<String, List<OrderItem>> skuIdOrderItemMap = orderItemList.stream().collect(Collectors.groupingBy(OrderItem::getSkuId));
            Set<Map.Entry<String, List<OrderItem>>> skuItemSet = skuIdOrderItemMap.entrySet();
            ordersService.update(new LambdaUpdateWrapper<Orders>().set(Orders::getStatus, "6"));
            for (Map.Entry<String, List<OrderItem>> skuItem : skuItemSet) {
                String skuId = skuItem.getKey();
                List<OrderItem> skuItemList = skuItem.getValue();
                Integer sumStock = skuItemList.stream().collect(Collectors.summingInt(OrderItem::getBuyCounts));
                ProductSku productSku = new ProductSku();
                productSku.setSkuId(skuId);
                productSku.setUpdateTime(new Date());
                productSku.setStock(sumStock);
                productSkuService.updateById(productSku);
            }
        }
    }
}
